<?php

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController
{
	public $layout = '//layouts/main';
	public $breadcrumbs = array();
	public $projectName;

	public function init()
	{
		if (isset($_REQUEST['project'])) {
			$this->projectName = $_REQUEST['project'];
		}
	}

	public function filters()
	{
		return array(
			array('application.components.AccessFilter - login - captcha - error'),
		);
	}

	protected function beforeAction($action)
	{
		if ($this->requireProject() && $this->projectName === null) {
			throw new CHttpException(400, 'Project name is required');
		}
		return parent::beforeAction($action);
	}

	/**
	 * Create url, forced to append project params
	 */
	public function createUrl($route, $params = array(), $ampersand = '&')
	{
		if (!isset($params['project']) && $this->projectName !== null && $this->requireProject($route)) {
			$params['project'] = $this->projectName;
		}
		return parent::createUrl($route, $params, $ampersand);
	}

	/**
	 * @param mixed $words set keywords of page
	 */
	public function setKeywords($words)
	{
		if (is_array($words)) {
			$words = implode(',', $words);
		}
		Yii::app()->clientScript->registerMetaTag($words, 'keywords');
	}

	/**
	 * @param string $text set description of page
	 */
	public function setDescription($text)
	{
		Yii::app()->clientScript->registerMetaTag($text, 'description');
	}

	/**
	 * Override this method to add page title
	 */
	public function getPageTitle()
	{
		$title = parent::getPageTitle();
		if (strpos($title, Yii::app()->name) === false) {
			$title .= ' - ' . Yii::app()->name;
		}
		return $title;
	}

	/**
	 * Rewrite TbBox title
	 */
	public function beginWidget($className, $properties = array())
	{
		if (strpos($className, 'TbBox') !== false && is_array($properties['title'])) {
			$title = CHtml::link('首页', array('site/index'));
			foreach ($properties['title'] as $text => $url) {
				if (is_null($url)) {
					continue;
				}
				$title .= '<span>/</span>' . (is_int($text) ? $url : CHtml::link($text, $url));
			}
			$properties['title'] = $title;
		}
		return parent::beginWidget($className, $properties);
	}

	/**
	 * Override this method to extract script/css snippets
	 */
	public function renderInternal($_viewFile_, $_data_ = null, $_return_ = false)
	{
		$content = parent::renderInternal($_viewFile_, $_data_, true);
		$content = preg_replace_callback('/<(script|style).*?(?:(media|pos)="(.+?)")?>(.+?)<\/\1>/s', array($this, 'extractSnippet'), $content);
		if ($_return_ === true) {
			return $content;
		}
		echo $content;
	}

	/**
	 * Extract script/css snippet as replace callback
	 */
	protected function extractSnippet($match)
	{
		static $count = 1;
		if ($match[1] === 'script' && $match[3] !== '') {
			$pos = @constant('CClientScript::POS_' . strtoupper($match[3]));
			if ($pos !== null) {
				$id = get_class($this) . '#js#' . $count++;
				Yii::app()->clientScript->registerScript($id, $match[4], $pos);
				return '';
			}
		} elseif ($match[1] === 'style') {
			$id = get_class($this) . '#css#' . $count++;
			Yii::app()->clientScript->registerCss($id, $match[4], $match[3]);
			return '';
		}
		return $match[0];
	}

	private function requireProject($route = null)
	{
		if ($route === null) {
			$route = $this->getRoute();
		}
		if ($route === 'project/create' || $route === 'project/index' || $route === 'api/error') {
			return false;
		}
		$route = trim($route, '/');
		if ($route === '' || ($pos = strpos($route, '/')) === false) {
			return $this->projectName !== null;
		}
		$c = strtolower(substr($route, 0, $pos));
		return ($c === 'api' || $c === 'project' || $c === 'data');
	}
}
